<template>
    <div class="lianxi">
        <el-container>
            <!-- 头部布局 -->
            <el-container class="main-container">
                <!-- 组件分类 -->
                <div class="component-categories">
                    <!-- 合并的选择行 -->
                    <div class="selection-and-tabs-row">
                        <!-- 左侧：组件库和表单模板选择 -->
                        <div class="left-selection">
                            <el-menu mode="horizontal">
                                <!-- 选择组件库 -->
                                <el-sub-menu index="1">
                                    <template #title>
                                        <i class="fas fa-cube"></i>
                                        {{ currentLibraryData.name || 'UI组件选择' }}
                                    </template>
                                    <el-menu-item v-for="(library, index) in availableLibraries" :key="library.id"
                                        :index="'1-' + index" @click="selectLibrary(library.id)"
                                        :class="{ 'is-active': selectedLibrary === library.id }">
                                        <i :class="library.icon"></i>
                                        {{ library.name }}
                                    </el-menu-item>
                                </el-sub-menu>

                            </el-menu>
                        </div>

                        <!-- 右侧：标签选择 -->
                        <div class="right-tabs">
                            <div class="category-tabs-small">
                                <button v-for="category in currentCategories" :key="category.id" class="tab-btn"
                                    :class="{ active: activeCategory === category.id }"
                                    @click="setActiveCategory(category.id)">
                                    <i :class="category.icon"></i>{{ category.name }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 标签页内容 -->
                    <div class="tab-content">
                        <!-- 动态渲染组件 -->
                        <div class="component-grid">
                            <div v-for="component in currentComponents" :key="component.id" class="component-item"
                                draggable="true" @dragstart="startDrag($event, component)"
                                :title="component.description">
                                <!-- <i :class="component.icon"></i> -->
                                <img :src="getIconPath(component.icon)" alt="" class="component-icon">
                                {{ component.name }}&lsaquo;{{ component.tag }}&rsaquo;
                            </div>
                        </div>
                    </div>
                </div>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import shuju from '@/assets/JSON/shuju.json';


defineOptions({
    name: 'LianXi' // 使用多单词名称
})

// 当前激活的标签页
const activeCategory = ref('container')

// 设置激活的标签页
const setActiveCategory = (category) => {
    activeCategory.value = category
}

// 组件库菜单状态
const isLibraryMenuOpen = ref(false)
const selectedLibrary = ref('html')

// 表单模板菜单状态
const selectedTemplate = ref(null)



// 选择组件库
const selectLibrary = (library) => {
    selectedLibrary.value = library
    isLibraryMenuOpen.value = false
    // 切换组件库时，自动设置第一个分类为激活状态
    const libraryData = shuju.componentLibraries[library]
    if (libraryData && libraryData.componentCategories && libraryData.componentCategories.length > 0) {
        activeCategory.value = libraryData.componentCategories[0].id
    }
    console.log('选择的组件库:', library)
}
// 获取可用的组件库列表
const availableLibraries = computed(() => {
    return Object.values(shuju.componentLibraries)
})


// 获取当前选中的表单模板数据
const currentTemplate = computed(() => {
    return selectedTemplate.value ? shuju.formTemplates.find(t => t.id === selectedTemplate.value) : null
})

// 获取当前选中组件库的数据
const currentLibraryData = computed(() => {
    return shuju.componentLibraries[selectedLibrary.value] || shuju.componentLibraries.html
})

// 获取当前选中组件库的分类列表
const currentCategories = computed(() => {
    return currentLibraryData.value.componentCategories || []
})

// 获取当前激活分类的组件列表
const currentComponents = computed(() => {
    const category = currentCategories.value.find(cat => cat.id === activeCategory.value)
    let components = category ? category.components : []

    // 如果选择了表单模板，根据模板字段筛选组件
    if (selectedTemplate.value && currentTemplate.value) {
        const templateFields = currentTemplate.value.fields
        components = components.filter(component => {
            // 根据组件的 id 或 type 匹配模板字段
            return templateFields.some(field =>
                component.id.includes(field) ||
                component.type === field ||
                component.tag === field
            )
        })
    }

    return components
})

// 拖拽开始事件
const startDrag = (event, componentData) => {
    event.dataTransfer.setData('text/plain', JSON.stringify(componentData))
}


// 获取图标路径
const getIconPath = (iconName) => {
    if (!iconName) return ''
    // 如果是FontAwesome图标类名，返回空字符串（使用CSS类）
    if (iconName.startsWith('fas ') || iconName.startsWith('fab ')) {
        return ''
    }

    // 确保路径使用正斜杠，并处理子目录
    const normalizedIconName = iconName.replace(/\\/g, '/')
    // console.log(`处理图标: ${iconName} -> ${normalizedIconName}`)

    // 简化方案：直接构造正确的URL路径
    try {
        // 获取当前模块的基础URL
        const currentUrl = new URL(import.meta.url)
        // 构造图标的绝对路径
        const iconUrl = new URL(`../icons/svg/${normalizedIconName}.svg`, currentUrl)
        // console.log(`生成图标URL: ${iconUrl.href}`)

        // 验证URL是否有效
        if (iconUrl.href && !iconUrl.href.includes('undefined')) {
            return iconUrl.href
        } else {
            throw new Error('生成的URL包含undefined')
        }
    } catch (error) {
        console.error(`图标路径生成失败 [${iconName}]:`, error)

        // 最后的备用方案：使用相对于网站根目录的路径
        const fallbackPath = `/src/icons/svg/${normalizedIconName}.svg`
        console.log(`使用备用路径: ${fallbackPath}`)
        return fallbackPath
    }
}


</script>
<!-- 样式 -->
<style scoped>
.lianxi {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 2px;
    background-color: antiquewhite;
}

/* 头部布局样式 */
.header-layout {
    display: flex;
    align-items: center;
    padding: 0 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    height: 60px;
}

.header-item {
    flex: 1;
    text-align: center;
    padding: 12px 16px;
    background: white;
    border: 1px solid #ced4da;
    border-radius: 4px;
    margin: 0 8px;
    font-weight: 500;
    color: #495057;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
}

.header-item:hover {
    background: #e9ecef;
    border-color: #adb5bd;
}

.header-item:first-child {
    margin-left: 0;
}

.header-item:last-child {
    margin-right: 0;
}

/* 下拉菜单样式 */
.dropdown-menu {
    position: relative;
}

.menu-title {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.menu-title i:first-child {
    color: #007bff;
}

.menu-title i:last-child {
    transition: transform 0.2s ease;
}

.menu-title i.rotated {
    transform: rotate(180deg);
    gap: 8px;
}

.menu-title i.fa-chevron-down {
    transition: transform 0.3s ease;
    font-size: 12px;
}

.menu-title i.fa-chevron-down.rotated {
    transform: rotate(180deg);
}

.dropdown-content {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    opacity: 0;
    visibility: hidden;
    transform: translateY(-10px);
    transition: all 0.3s ease;
    display: flex;
    flex-direction: row;
    min-width: 400px;
    margin-top: 4px;
}

.dropdown-content.show {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
}

.menu-item {
    flex: 1;
    padding: 12px 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    border-right: 1px solid #e4e7ed;
    font-size: 14px;
    color: #606266;
}

.menu-item:last-child {
    border-right: none;
}

.menu-item:hover {
    background-color: #f0f9ff;
    color: #409eff;
}

.menu-item.selected {
    background-color: #409eff;
    color: white;
}

.menu-item.selected:hover {
    background-color: #337ecc;
    color: white;
}

.menu-item i {
    font-size: 16px;
}

/* 主容器样式 */
.main-container {
    /* height: calc(100vh - 120px); */
    width: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    flex-direction: column;
    background-color: #fafafa;
    overflow-y: auto;
}

/* 标签页容器 */
.tab-container {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
    background-color: white;
}

.tab-item {
    flex: 1;
    padding: 12px 16px;
    text-align: center;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
    font-size: 14px;
    color: #606266;
}

.tab-item.active {
    color: #409eff;
    border-bottom-color: #409eff;
    background-color: #f0f9ff;
}

.tab-item:hover:not(.active) {
    background-color: #f5f7fa;
    color: #409eff;
}

.tab-item i {
    margin-right: 6px;
}

/* 组件分类样式 */
.component-categories {
    padding: 16px;
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

/* 合并行布局样式 */
.selection-and-tabs-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 2px;
    margin-bottom: 2px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

/* 左侧选择区域 */
.left-selection {
    flex: 0 0 auto;
    min-width: 170px;
    height: 50px;
}

.left-selection .el-menu--horizontal {
    display: flex;
    align-items: center;
    border-bottom: none !important;
    background: transparent;
}

.left-selection .el-sub-menu {
    margin-right: 20px;
}

.left-selection .el-sub-menu:last-child {
    margin-right: 0;
}

.left-selection .el-sub-menu .el-sub-menu__title {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 16px;
    font-size: 14px;
    border-radius: 6px;
    background: #409eff;
    color: white;
    border: none;
    min-width: 150px;
}

.left-selection .el-sub-menu .el-sub-menu__title:hover {
    background: #337ecc;
}

.left-selection .el-sub-menu .el-sub-menu__title i {
    font-size: 14px;
}

/* 右侧标签区域 */
.right-tabs {
    flex: 1;
    display: flex;
    /* justify-content: flex-end; */
}

.right-tabs .category-tabs-small {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 0;
}

/* 小按钮样式的标签页导航 */
.category-tabs-small {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.tab-btn {
    padding: 8px 16px;
    border: 1px solid #e4e7ed;
    /* border-radius: 20px; */
    background-color: white;
    color: #606266;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s ease;
    outline: none;
    white-space: nowrap;
    display: flex;
    align-items: center;
    gap: 6px;
}

.tab-btn:hover {
    border-color: #409eff;
    color: #409eff;
    background-color: #f0f9ff;
}

.tab-btn.active {
    background-color: #409eff;
    border-color: #409eff;
    color: white;
    font-weight: 500;
}

.tab-btn i {
    font-size: 12px;
}

/* 标签页内容样式 */
.tab-content {
    flex: 1;
    background-color: white;
    border-radius: 4px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    /* min-height: 200px; */
}



/* 组件网格 */
.component-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: flex-start;
    align-items: flex-start;
    transition: all 0.3s ease;
    overflow: hidden;
}

@keyframes slideDown {
    from {
        opacity: 0;
        max-height: 0;
    }

    to {
        opacity: 1;
        max-height: 500px;
    }
}

.component-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: white;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 12px;
    color: #606266;
    flex: 0 0 auto;
    white-space: nowrap;
    min-width: 80px;
    /* max-width: 120px; */
}

.component-item:hover {
    border-color: #409eff;
    background-color: #f0f9ff;
    color: #409eff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.component-item i {
    margin-right: 8px;
    font-size: 16px;
    color: #909399;
}

.component-item:hover i {
    color: #409eff;
}

/* Element UI 菜单选中状态样式 */
.el-menu-item.is-active {
    background-color: #ecf5ff !important;
    color: #409eff !important;
    border-bottom: 2px solid #409eff;
}

.el-menu-item.is-active i {
    color: #409eff;
}

.el-menu-item:hover {
    background-color: #f5f7fa;
    color: #409eff;
}

.el-sub-menu .el-sub-menu__title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.el-sub-menu .el-sub-menu__title i {
    font-size: 14px;
}

/* 滚动条样式 */
.main-container::-webkit-scrollbar {
    width: 6px;
}

.main-container::-webkit-scrollbar-track {
    background: #f1f1f1;
}

.main-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.main-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.component-categories::-webkit-scrollbar {
    width: 6px;
}

.component-categories::-webkit-scrollbar-track {
    background: #f1f1f1;
}

/* 组件图标样式 */
.component-icon {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    vertical-align: middle;
    flex-shrink: 0;
}


.component-categories::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.component-categories::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>